package com.xiyun.admin.service.impl;

import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xiyun.common.response.exceptions.XiYunException;
import com.xiyun.common.response.result.R;
import com.xiyun.admin.client.VodClient;
import com.xiyun.admin.entity.SubjectVideo;
import com.xiyun.admin.mapper.SubjectVideoMapper;
import com.xiyun.admin.service.SubjectVideoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class SubjectVideoServiceImpl extends ServiceImpl<SubjectVideoMapper, SubjectVideo> implements SubjectVideoService {

    @Autowired
    private VodClient vodClient;

    @Override
    public boolean removeVideoBySubjectId(String subjectId) {
        //根据课程id查询所有小节视频id
        List<String> videos = removeVideos(subjectId);

        QueryWrapper<SubjectVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id",subjectId);
        baseMapper.delete(wrapper);

        if (videos.size() > 0) {
            R r = vodClient.deleteVideosBatch(videos);
            if (r.getCode() == 20001){
                throw new XiYunException(20001,"删除课程失败,熔断器已将请求降级执行...");
            }
        }
        return true;
    }

    private List<String> removeVideos(String subjectId){
        QueryWrapper<SubjectVideo> wrapper = new QueryWrapper<>();
        wrapper.eq("subject_id",subjectId);
        wrapper.select("video_source_id");
        List<SubjectVideo> videoList = baseMapper.selectList(wrapper);

        List<String> videoIds = new ArrayList<>(videoList.size());
        for (SubjectVideo video : videoList) {
            String id = video.getVideoSourceId();
            if (!StringUtils.isEmpty(id))
                videoIds.add(id);
        }
        return videoIds;
    }
}
